import Common
from M3u8List import M3u8 

class M3u8Reader:
   
    def __init__(self, fileName):
        tempFile = open(fileName)
        self.m3u8 = M3u8()
        
        while 1:
            line = tempFile.readline()
            if not line:
                break
            else:
                line = line.rstrip('\n')
                if Common.strContains(line, "TARGETDURATION"):
                    self.ParseTargetDuration(line)
                elif Common.strContains(line, "MEDIA-SEQUENCE"):
                    self.ParseMediaSequence(line)
                elif Common.strContains(line, "EXTINF"):
                    self.ParseTS(line, tempFile.readline().rstrip('\n'))
    
    def getM3u8(self):
        return self.m3u8

    def ParseTS(self, meta, TS_File):
        self.m3u8.InsertTS(TS_File, meta)
    
    def ParseTargetDuration(self, line):
        temp = line.split(":")
        self.m3u8.header[M3u8.TargetDuration] = int(temp[1])

    def ParseMediaSequence(self, line):
        temp = line.split(":")
        self.m3u8.header[M3u8.MediaSeq] = int(temp[1])
    